// 前端并发控制

/*
// 请求的相关参数选项
interface Option {
    url: string,
    method: string,
    params: Object,
    success: (value: any) => any,
    error: (value: any) => any
}
*/

/**
 * @param {[Option]} options 请求的数组
 * @param {Number} max 最大同时请求数
 */
function sendRequest(options, max = 1) {
    // 超出最大请求数时，对超出的请求进行保存
    const queue = []
    // 并发的请求数
    let count = 0

    options.forEach(option => request(option))

    /**
     * @param {Option} opt
     */
    async function request(opt) {
        count++
        if (count > max) {
            // resolve不被调用就不会执行下面的请求，阻塞
            await new Promise(resolve => queue.push(resolve))
        }
        // 执行请求
        await http(opt).then(opt.success, opt.error)
        // 弹出并调用队头的resolve，释放阻塞
        const resolve = queue.shift()
        resolve && resolve()
    }
}

/**
 * @param opt
 */
async function http(opt) {
    // get
    if (opt.method.toLocaleUpperCase() === 'GET') {
        const url = opt.params
            ? Object.keys(opt.params).map(key => `${key}=${opt.params[key]}`)
            : []
        return await fetch(opt.url + url.join('&')).then(response => response)
    }
}


// test
const options = [
    { method: 'GET', url: 'http://127.0.0.1:550/', params: {}, success: res => console.log(res), error: err => console.log(err)},
    { method: 'GET', url: 'http://127.0.0.1:5500/', params: {}, success: res => console.log(res) },
    { method: 'GET', url: 'http://127.0.0.1:5500/', params: {}, success: res => console.log(res) },
    { method: 'GET', url: 'http://127.0.0.1:5500/', params: {}, success: res => console.log(res) }
]
sendRequest(options, 2)
